package com.example.userservice.util;

import com.example.userservice.entity.Detail;
import com.example.userservice.entity.Log;
import com.example.userservice.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.log.LogMessage;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class LogHelper {

    private static final Logger logger = LoggerFactory.getLogger(LogHelper.class);


    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 构建一个日志对象（可用于打印或持久化）
     */
    public Log buildLog(Long userId, String action, String ip, Object detailObj) {
        try {
            String detailJson = objectMapper.writeValueAsString(detailObj);
            return new Log(null, userId, action, ip, detailJson);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("日志详情序列化失败", e);
        }
    }

    /**
     * 打印日志（info 级别）
     */
    public void printLog(Log log) {
        logger.info("[操作日志] 用户ID: {}, 动作: {}, IP: {}, 详情: {}",
                log.getUserId(), log.getAction(), log.getIp(), log.getDetail());
        rocketMQTemplate.asyncSend("log-topic", log, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("[异步发送日志成功]: {}",sendResult);
            }
            @Override
            public void onException(Throwable throwable) {
                logger.warn("[异步发送失败，尝试同步发送]: ",throwable);
                try {
                    SendResult result = rocketMQTemplate.syncSend("log-topic", log,3000);
                    logger.info("[同步发送成功]: {}",result);
                } catch (Exception e) {
                    logger.error("[同步发送失败]:",e);
                }
            }
        });
    }


    /**
     * 快捷构建：多字段变更日志
     */
    public Log buildFieldLog(Long userId, String action, String ip,
                             List<Detail> detailList) {
        return buildLog(userId, action, ip, detailList);
    }
    public List<Detail> compareUserChanges(User oldUser, User newUser) {
        List<Detail> changes = new ArrayList<>();

        if (newUser.getUserName() != null && !newUser.getUserName().equals(oldUser.getUserName())) {
            changes.add(new Detail("username", oldUser.getUserName(), newUser.getUserName()));
        }

        if (newUser.getEmail() != null && !newUser.getEmail().equals(oldUser.getEmail())) {
            changes.add(new Detail("email", oldUser.getEmail(), newUser.getEmail()));
        }

        if (newUser.getPhone() != null && !newUser.getPhone().equals(oldUser.getPhone())) {
            changes.add(new Detail("phone", oldUser.getPhone(), newUser.getPhone()));
        }

        return changes;
    }

}
